package com.example.demo.filter;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RequestFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        getIp(servletRequest);
        showParams(servletRequest);
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("执行时长 ："+(System.currentTimeMillis()-start));
    }

    @Override
    public void destroy() {

    }

    /**
     * 打印ip
     * @param servletRequest
     */
    private void getIp(ServletRequest servletRequest){
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        log.info("客户端访问ip：" + ip);
    }

    /**
     * 打印入参
     * @param servletRequest
     */
    private void showParams(ServletRequest servletRequest) throws IOException {
        /*HttpServletRequest request = (HttpServletRequest)servletRequest;
        request.getParameterMap();
        request.getParameterNames();
        BufferedReader  streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
        StringBuilder builder = new StringBuilder();
        String line ;
        while ((line = streamReader.readLine()) != null){
            builder.append(line);
        }
        System.out.println(JSONObject.parseObject(builder.toString()));*/
    }
}
